package com.kyle.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kyle.dao.RoleDao;
import com.kyle.dao.UserDao;
import com.kyle.entity.DeptEntity;
import com.kyle.entity.RoleEntity;
import com.kyle.entity.UserEntity;
import com.kyle.entity.util.JsonResult;
import com.kyle.entity.util.PageBean;

@Controller
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/user")
public class UserAction {

	@Autowired
	@Qualifier(value="userDao")
	private UserDao userDao;
	
	@RequestMapping(value="/getUserListByDeptId.xhtml")
	@ResponseBody
	public JsonResult getUserListByDeptId(PageBean pageBean,Integer pid,String username,String truename,
			HttpServletRequest request,HttpServletResponse response){
		JsonResult jsonResult = new JsonResult();
		
		StringBuilder queryFromSb = new StringBuilder();
		queryFromSb.append("o.deptid=?");
		
		List<Object> params = new ArrayList<Object>();
		params.add(pid);//选择条件
		
		//前台查找条件
		if(username!=null){
			queryFromSb.append(" and o.username like ? ");
			params.add("%"+username+"%");
		}
		if(truename!=null){
			queryFromSb.append(" and o.truename like ? ");
			params.add("%"+truename+"%");
		}
		List<UserEntity> userList = userDao.getScrollData(pageBean, queryFromSb.toString(), params.toArray(), null);
		Object rows = userDao.getScrollDataCount(queryFromSb.toString(), params.toArray());
		jsonResult.setTotal(rows);
		jsonResult.setRows(userList);
		return jsonResult;
	}
	
	@RequestMapping(value="/addUser.xhtml")
	@ResponseBody
	public JsonResult addUser(UserEntity userEntity,HttpServletRequest request,HttpServletResponse response){
		JsonResult jsonResult = new JsonResult();
		try {
			userDao.saveEntity(userEntity);
			jsonResult.setMsg("添加成功");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jsonResult.setState(false);
			jsonResult.setMsg("添加失败");
		}		
		return jsonResult;
	}
}
